package database

import (
	"log"

	_ "github.com/go-sql-driver/mysql" //加载mysql
	"github.com/jinzhu/gorm"

	"go-papers/models/mysql"
)

var Eloquent *gorm.DB

func Setup() {
	Host := GetMysqlHost()
	DbType := GetDatabaseType()
	conn := GetMysqlConnect()

	//log.Println( DbType , conn)
	if DbType != "mysql" && DbType != "sqlite3" {
		log.Println("db type unknow")
	}
	var err error
	var db Database
	if DbType == "mysql" {
		db = new(Mysql)
		Eloquent, err = db.Open(DbType, conn)

	} else if DbType == "sqlite3" {
		db = new(SqlLite)
		Eloquent, err = db.Open(DbType, Host)

	} else {
		panic("db type unknow")
	}
	if err != nil {
		log.Fatalf("%s connect error %v", DbType, err)
	} else {
		log.Printf("%s connect success!", DbType)
	}
	if Eloquent.Error != nil {
		log.Fatalf("database error %v", Eloquent.Error)
	}
	Eloquent.LogMode(true)
}

//默认基础 mysql local 配置
func GetMysqlConnect() string {
	return mysql.LocalDb.MasterDNS()
}

func GetMysqlHost() string {
	return mysql.LocalDb.MasterHost()
}

func GetDatabaseType() string {
	return mysql.LocalDb.MasterDriver()
}

type Database interface {
	Open(dbType string, conn string) (db *gorm.DB, err error)
}

type Mysql struct {
}

func (*Mysql) Open(dbType string, conn string) (db *gorm.DB, err error) {
	eloquent, err := gorm.Open(dbType, conn)
	return eloquent, err
}

type SqlLite struct {
}

func (*SqlLite) Open(dbType string, conn string) (db *gorm.DB, err error) {
	eloquent, err := gorm.Open(dbType, conn)
	return eloquent, err
}
